import 'package:flutter/material.dart';
import 'package:mi_mang_flutter/utils/locale_util.dart';

import 'package:mi_mang_flutter/utils/shared_preferences.dart';

class LocaleProvider extends ChangeNotifier {
  static const localeValueList = ['', 'zh-CN', 'en'];

  static const _APPLOCALEINDEX = 'AppLocaleIndex';

  List<Locale> get supportedLocales => <Locale>[
        Locale("en", ""),
        Locale("zh", "CN"),
      ];

  /// 系统语言(如: "zh", "en")
  static String? systemLanguageCode;

  /// 语言(如: "zh", "en")
  static String? languageCode = "en";
  int? _localeIndex;

  int? get localeIndex => _localeIndex;

  Locale? get locale {
    if (_localeIndex! > 0) {
      var value = localeValueList[_localeIndex!].split("-");
      return Locale(value[0], value.length == 2 ? value[1] : '');
    }
    // var code = WidgetsBinding.instance.window.locale.languageCode ?? "en";
    // // 跟随系统
    // return supportedLocales.firstWhere((element) {
    //   return element.languageCode == code;
    // }, orElse: () => supportedLocales[0]);
    if (systemLanguageCode != null) {
      return supportedLocales.firstWhere((element) {
        return element.languageCode == systemLanguageCode;
      }, orElse: () => supportedLocales[0]);
    }
    return null;
  }

  LocaleProvider() {
    _localeIndex = SpUtil.getInt(_APPLOCALEINDEX, defValue: 0);
    LocaleProvider.systemLanguageCode = _localeLanguageCode();
    LocaleProvider.languageCode = _localeLanguageCode();
  }

  systemLocale(Locale locale) {
    var code = locale.languageCode;
    // 跟随系统
    var localeModel = supportedLocales.firstWhere((element) {
      return element.languageCode == code;
    }, orElse: () => supportedLocales[0]);
    LocaleProvider.systemLanguageCode = localeModel.languageCode;
    LocaleProvider.languageCode = _localeLanguageCode();
    notifyListeners();
  }

  switchLocale(int? index) {
    _localeIndex = index;
    notifyListeners();
    SpUtil.putInt(_APPLOCALEINDEX, index);
    LocaleProvider.languageCode = _localeLanguageCode();
  }

  static String localeName(index, context) {
    switch (index) {
      case 0:
        return i18n(context).autoBySystem;
      case 1:
        return "简体中文";
      case 2:
        return 'English';
      default:
        return '';
    }
  }

  String? _localeLanguageCode() {
    if (locale != null) {
      return locale!.languageCode;
    }
    return LocaleProvider.systemLanguageCode;
  }
}
